import React, { Component, useMemo } from 'react'
import { View } from '@tarojs/components'
import Taro, { getCurrentInstance } from '@tarojs/taro'
import { timestampToTime, transformData } from '@/utils'
import { SpNavBar } from '@/components'
import api from '@/api'
import './form.scss'
import UploadUtil from '@/utils/UploadUtil'
import { connect } from 'react-redux'
import FormImageItem from './comps/form-image-item'
import {
    Form,
    Input,
    Button,
    ImageUploader,
    Dialog,
    TextArea,
    DatePicker,
    CascadePicker,
    Cascader,
    Stepper,
    Switch,
    Checkbox,
    Space,
    Radio,
    Selector,
    Picker,
    Popup,
    SearchBar,
    CheckList
} from 'antd-mobile'
import dayjs from 'dayjs'
import {
    TAG_MAP,
    SELECCAT_MAP,
    BRAND_MAP2,
    GOOD_MAP,
    PIC
} from '../good/const'
import { forEach, values } from 'lodash'


const COUPON_TYPE = {
    'discount': '折扣券',
    'cash': '满减券',
    'new_gift': '兑换券'
}
const basicColumns = [
    [
        { label: '00时', value: '00' },
        { label: '01时', value: '01' },
        { label: '02时', value: '02' },
        { label: '03时', value: '03' },
        { label: '04时', value: '04' },
        { label: '05时', value: '05' },
        { label: '06时', value: '06' },
        { label: '07时', value: '07' },
        { label: '08时', value: '08' },
        { label: '09时', value: '09' },
        { label: '10时', value: '10' },
        { label: '11时', value: '11' },
        { label: '12时', value: '12' },
        { label: '13时', value: '13' },
        { label: '14时', value: '14' },
        { label: '15时', value: '15' },
        { label: '16时', value: '16' },
        { label: '17时', value: '17' },
        { label: '18时', value: '18' },
        { label: '19时', value: '19' },
        { label: '20时', value: '20' },
        { label: '21时', value: '21' },
        { label: '22时', value: '22' },
        { label: '23时', value: '23' },

    ],
    [
        { label: '00分', value: '00' },
        { label: '30分', value: '30' },
    ],
]

@connect(({ planSelection }) => ({
    planSelection: planSelection.activeShop
}))
export default class List extends Component {
    formRef = React.createRef()

    constructor(props) {
        super(props)
        this.state = {
            couponStr: '',
            items: [],
            is_ziti: false,
            is_delivery: false,
            logo: [],
            banner: [],
            form: {
                shop_code: '',
                name: '',
                contact: '',
                mobile: '',
                startTime: [],
                endTime: [],
                hour: '',
                is_ziti: false,
                is_delivery: false,
                lng: 121.418211,
                lat: 31.175317,
                regions: [],
                regions_id: [],
                introduce: '',
                logo: '',
                banner: '',
                address: '',

            },
        }
    }
    async componentWillUnmount() {
        console.log('2222')

    }
    // filteredItems = useMemo(() => {
    //     if (this.state.searchText) {
    //       return items.filter(item => item.includes(this.state.searchText))
    //     } else {
    //       return items
    //     }
    //   }, [items])
    async componentDidMount() {
        const {
            router: {
                params: { id }
            }
        } = getCurrentInstance()
        if (!id) {
            this.setState({
                couponStr: '添加店铺'
            })
        } else {
            this.setState({
                couponStr: '编辑店铺'
            })
            this.getShopDetail(id)
        }
        this.getAdressItem()
    }

    async componentDidShow() {
        console.log('dianwu h5 comonentDidShow...')

    }
    async getAdressItem() {
        const data = await api.address.areaList()
         this.setState({
            items: data
        })

    }
    async getShopDetail(id) {
        const form = await api.shop.getMerchantById({ 'distributor_id': id })
        for (const key in this.state.form) {
            this.state.form[key] = form[key]
        }
        console.log('this.state.form',this.state.form)
     this.setState({
            // form: form,
            is_ziti: form.is_ziti,
            is_delivery: form.is_delivery,
            logo: !!form.logo && (form.logo.length > 0) ? [form.logo] : [],
            banner: !!form.banner && form.banner.length > 0 ? [form.banner] : []
        })
        let hour2 = form.hour?.split('-')
        form.startTime = hour2[0].split(':')
        if(form.startTime.length >=2 && form.startTime[0].length >0 && form.startTime[1].length >0){
        }else{
            form.startTime = []
        }
        form.endTime = hour2[1].split(':')
        if(form.endTime.length >=2 && form.endTime[0].length >0 && form.endTime[1].length >0){
         
        }else{
            form.endTime = []
        }
        this.formRef.current?.setFieldsValue(form)

    }
    onSubmit = async () => {

        const values = this.formRef.current?.getFieldsValue()
        // Dialog.alert({
        //     content: <pre>{JSON.stringify(values, null, 2)}</pre>,
        // })

        let params = this.state.form
        params = {
            ...params,
            ...JSON.parse(JSON.stringify(values)),
        }
        params.startTime = params.startTime.join(':')
        params.endTime = params.endTime.join(':')
        params.hour = params.startTime + '-' + params.endTime
        if (this.state.logo.length > 0) {
            params.logo = this.state.logo[0]
        } else {
            params.logo = ''
        }
        if (this.state.banner.length > 0) {
            params.banner = this.state.banner[0]
        } else {
            params.banner = ''
        }
        console.log(params)
        const {
            router: {
                params: { id }
            }
        } = getCurrentInstance()
        if (!id) {
            await api.shop.addShop(params)
        } else {
            params.distributor_id = id
            await api.shop.editMerchant(params)
        }


        Taro.navigateBack()
    }
    onFinish = (values) => {
        console.log(values)
        if (values.quantity) {

        }
        this.onSubmit(values)
    }
    onFinishFailed = (values) => {
        // Dialog.alert({
        //     content: <pre>{JSON.stringify(values, null, 2)}</pre>,
        // })
    }

    render() {
        const form = this.state.form
        return (
            <View className='creat-form'>
                <SpNavBar title={this.state.couponStr} />
                <Form
                    ref={this.formRef}
                    layout='horizontal'
                    footer={
                        <Button block type='submit' color='primary' size='large' >
                            提交
                        </Button>
                    }
                    onFinish={this.onFinish}
                    onFinishFailed={this.onFinishFailed}
                    initialValues={{}}
                >
                    <Form.Header>基础信息</Form.Header>
                    <Form.Item label='店铺号' name='shop_code'
                        rules={[{ required: true, message: '字母、数字' }]}
                    >
                        <Input value='' placeholder='店铺号(字母、数字)' />
                    </Form.Item>
                    <Form.Item label='店铺名称' name='name'
                        rules={[{ required: true, message: '店铺名称' }]}
                    >
                        <Input placeholder='请输入店铺名称' />
                    </Form.Item>
                    <Form.Item
                        name='contact'
                        label='联系人姓名'
                        rules={[{
                            required: true,
                            message: '联系人姓名',
                        }]}
                    >
                        <Input onChange={console.log} placeholder='请输入联系人姓名' />
                    </Form.Item>

                    <Form.Item
                        name='mobile'
                        label='联系方式'
                        rules={[{
                            required: true,
                            message: '联系方式',
                            // pattern: '(^1[3-9]\\d{9}$)'
                        }]}
                    >
                        <Input onChange={console.log} placeholder='请输入联系方式' />
                    </Form.Item>
                    <Form.Item
                        name='contract_phone'
                        label='固定座机'
                    >
                        <Input onChange={console.log} placeholder='请输入固定座机' />
                    </Form.Item>
                    <Form.Item label="经营开始时间" name='startTime'
                        trigger='onConfirm'
                        rules={[{ required: true, message: '开始时间不能为空' }]}
                        onClick={(e, datePickerRef) => {
                            datePickerRef.current?.open() // ⬅️
                        }}
                    >
                        <Picker
                            columns={basicColumns}
                        >
                            {value => value.length > 0 ? value[0].value + ':' + value[1].value : '请选择开始时间'}
                        </Picker>
                    </Form.Item>
                    <Form.Item label="经营结束时间" name='endTime'
                        trigger='onConfirm'
                        rules={[{ required: true, message: '结束时间不能为空' }]}
                        onClick={(e, datePickerRef) => {
                            datePickerRef.current?.open() // ⬅️
                        }}
                    >
                        <Picker
                            columns={basicColumns}
                        >
                            {value => value.length > 0 ? value[0].value + ':' + value[1].value : '请选择结束时间'}
                        </Picker>
                    </Form.Item>
                    {/* <Form.Header>适用规则</Form.Header> */}
                    <Form.Item
                        name='is_delivery'
                        label='是否快递'
                        valuePropName='checked'
                    >
                        <Switch />
                    </Form.Item>


                    <Form.Item
                        label='店铺图片'
                    >
                        <Space>
                            <FormImageItem
                                label='店铺logo：'
                                key='000'
                                onChange={(item) => {
                                    this.setState({
                                        logo: [...item]
                                    })
                                }}
                                value={this.state.logo}
                            />
                            <FormImageItem
                                label='店铺背景：'
                                key='288'
                                onChange={(item) => {
                                    this.setState({
                                        banner: [...item]
                                    })
                                }}
                                value={this.state.banner}
                            />
                        </Space>
                    </Form.Item>
                    <Form.Item
                        name='is_ziti'
                        label='是否自提'
                        valuePropName='checked'
                        help='启用到店自提功能后，买家下单时可选择下方地址自提，下单后你需要尽快将商品配送至指定自提点；下方自提地址共享该店铺库存。'
                    >
                        <Switch />
                    </Form.Item>
                    {/* <Form.Subscribe to={['is_ziti']}>
                        {({ is_ziti }) => (
                            <>
                                {is_ziti === true && (
                                    <>
                                        <Form.Item label="最低可用(元)" name='least_cost'
                                            rules={[{ required: true, message: '最低可用金额不能为空' }]}
                                        >
                                            <Input placeholder='满多少元可用,请输入金额' />
                                        </Form.Item>
                                    </>

                                )}
                            </>
                        )}
                    </Form.Subscribe> */}
                    {this.state.couponStr === '添加店铺' && (<><Form.Item label="店铺地址" name='regions_id'
                        trigger='onConfirm'
                        rules={[{ required: true, message: '请选择地址' }]}
                        onClick={(e, datePickerRef) => {
                            datePickerRef.current?.open() // ⬅️
                        }}
                    >
                        <Cascader
                            options={this.state.items}
                            value={this.state.form.regions_id}
                            onChange
                        >
                            {items => {
                                console.log(items)
                                if (items.every(item => item === null)) {
                                    return '未选择'
                                } else {
                                    this.state.form.regions = items.map(item => item?.label ?? '未选择')
                                    return items.map(item => item?.label ?? '未选择').join('-')
                                }
                            }}
                        </Cascader>
                    </Form.Item>
                        <Form.Item name='address' label='详细地址'
                            rules={[{ required: true, message: '详细地址不能为空' }]}>
                            <TextArea
                                placeholder='请填写详细地址'
                                maxLength={100}
                                showCount
                            />
                        </Form.Item></>)}

                    <Form.Item name='introduce' label='店铺介绍'>
                        <TextArea
                            placeholder='请输入店铺介绍'
                            maxLength={300}
                            showCount
                        />
                    </Form.Item>
                </Form>
            </View >

        )
    }
}
